package com.hsjk.szwj.module.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.module.pay.constant.PayOrderConstant;
import com.hsjk.szwj.module.pay.constant.PayOrderDivisionConstant;
import com.hsjk.szwj.module.pay.dal.dataobject.order.PayOrderDO;
import com.hsjk.szwj.module.pay.dal.dataobject.order.PayOrderDivisionRecordDO;
import com.hsjk.szwj.module.pay.dal.mysql.IPayOrderDivisionRecordMapper;
import com.hsjk.szwj.module.pay.dal.mysql.IPayOrderMapper;
import com.hsjk.szwj.module.pay.util.SeqKit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/25 01:31
 **/
@Service
public class PayOrderDivisionRecordService extends ServiceImpl<IPayOrderDivisionRecordMapper, PayOrderDivisionRecordDO> {

    @Resource
    private IPayOrderMapper payOrderMapper;


    /**
     * 更新分账记录为分账成功  ( 单条 )  将：  已受理 更新为： 其他状态
     **/
    public void updateRecordSuccessOrFailBySingleItem(Long recordId, Integer state,
                                                      String channelRespResult) {

        PayOrderDivisionRecordDO updateRecord = new PayOrderDivisionRecordDO();
        updateRecord.setState(state);
        // 若明确成功，清空错误信息。
        updateRecord.setChannelRespResult(state == PayOrderDivisionConstant.STATE_SUCCESS
                ? "" : channelRespResult);
        update(updateRecord, new LambdaQueryWrapper<PayOrderDivisionRecordDO>()
                .eq(PayOrderDivisionRecordDO::getPayOrderId, recordId)
                .eq(PayOrderDivisionRecordDO::getState,
                        PayOrderDivisionConstant.STATE_ACCEPT));

    }


    /**
     * 更新分账记录为分账成功
     **/
    public void updateRecordSuccessOrFail(List<PayOrderDivisionRecordDO> records,
                                          Integer state, String channelBatchOrderId,
                                          String channelRespResult) {

        if (records == null || records.isEmpty()) {
            return;
        }

        List<Long> recordIds = new ArrayList<>();
        records.stream().forEach(r -> recordIds.add(r.getId()));

        PayOrderDivisionRecordDO updateRecord = new PayOrderDivisionRecordDO();
        updateRecord.setState(state);
        updateRecord.setChannelBatchOrderId(channelBatchOrderId);
        updateRecord.setChannelRespResult(channelRespResult);
        update(updateRecord, new LambdaQueryWrapper<PayOrderDivisionRecordDO>()
                .in(PayOrderDivisionRecordDO::getId, recordIds)
                .eq(PayOrderDivisionRecordDO::getState, PayOrderDivisionConstant.STATE_WAIT));

    }

    /**
     * 更新分账订单为： 等待分账中的状态
     **/
    @Transactional
    public void updateResendState(String payOrderId) {

        PayOrderDO updateRecord = new PayOrderDO();
        updateRecord.setDivisionState(PayOrderConstant.DIVISION_STATE_WAIT_TASK);

        // 更新订单
        int payOrderUpdateRow = payOrderMapper.update(updateRecord, new LambdaQueryWrapper<PayOrderDO>()
                .eq(PayOrderDO::getId, payOrderId)
                .eq(PayOrderDO::getDivisionState, PayOrderConstant.DIVISION_STATE_FINISH));

        if (payOrderUpdateRow <= 0) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "更新订单分账状态失败");
        }

        PayOrderDivisionRecordDO updateRecordByDiv = new PayOrderDivisionRecordDO();
        // 重新生成batchOrderId, 避免部分失败导致： out_trade_no重复。
        updateRecordByDiv.setBatchOrderId(SeqKit.genDivisionBatchId());
        //待分账
        updateRecordByDiv.setState(PayOrderDivisionConstant.STATE_WAIT);
        updateRecordByDiv.setChannelRespResult("");
        updateRecordByDiv.setChannelBatchOrderId("");
        boolean recordUpdateFlag = update(updateRecordByDiv,
                new LambdaQueryWrapper<PayOrderDivisionRecordDO>()
                        .eq(PayOrderDivisionRecordDO::getPayOrderId, payOrderId)
                        .eq(PayOrderDivisionRecordDO::getState, PayOrderDivisionConstant.STATE_FAIL)
        );

        if (!recordUpdateFlag) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "更新分账记录状态失败");
        }
    }
}
